package com.courage.crawler.boss.service.crawler;

import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;

import java.util.Collections;
import java.util.LinkedList;

@Slf4j
public class CrawlerEngine {

    static {
        System.setProperty("webdriver.chrome.driver", "/usr/local/bin/chromedriver");
    }

    private LinkedList<CrawlerRule> rules = new LinkedList();

    private String homePage;

    public CrawlerEngine(String homePage) {
        this.homePage = homePage;
    }

    //进入首页之后 , 执行的爬虫规则
    public void registerCrawlerRule(CrawlerRule baseCrawlerRule) {
        rules.add(baseCrawlerRule);
    }

    public void startup() {
        try {
            ChromeDriverContext chromeDriverContext = homePage();
            while (!chromeDriverContext.willstop()) {
                for (CrawlerRule rule : rules) {
                    rule.doAction(chromeDriverContext);
                }
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {
                }
            }
        } catch (Exception e) {
            log.error("startup error:", e);
        }
    }

    private ChromeDriverContext homePage() throws InterruptedException {
        ChromeOptions chromeOptions = buildGlobalOptions();
        ChromeDriver driver = new ChromeDriver(chromeOptions);
        driver.get(this.homePage);
        //浏览器窗口变大
        driver.manage().window().maximize();
        Thread.sleep(20000);
        //定位输入框元素
        WebElement txtbox = driver.findElement(new By.ByCssSelector(".search-input-box input"));
        //在输入框输入文本
        txtbox.sendKeys("自动驾驶");
        //鼠标移动空白处，以免无法点击城市
        clickBlankArea(driver);
        log.info("进入首页了，封装上下文对象");
        ChromeDriverContext chromeDriverContext = new ChromeDriverContext();
        chromeDriverContext.setChromeDriver(driver);
        return chromeDriverContext;
    }

    private ChromeOptions buildGlobalOptions() {
        ChromeOptions option = new ChromeOptions();
        // 版本：v88以上 设置window.navigator.webdriver 为 false
        option.addArguments("--disable-blink-features=AutomationControlled");
        // 移除 控制文字
        option.setExperimentalOption("useAutomationExtension", false);
        option.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"));
        return option;
    }

    public static void clickBlankArea(WebDriver driver) {
        Actions actions = new Actions(driver);
        actions.moveByOffset(0, 0).click().build().perform();
    }

}